/* eslint-disable  */
import { Variable } from "@/api/interface/iot";
import { addInfo, delInfo, exportVariableExcel, getPageList, importVariableExcel, modInfo } from "@/api/modules/iot/variable";
import Empty from "@/components/Empty";
import { deptAnonymous } from "@/utils/constants";
import { JsonSchemaEmitParam } from "@/components/JsonSchemaForm/interface/jsonschema";
import { TYPE_NAME } from "@/components/JsonSchemaForm/type/type";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import SensorHistory from "@/components/Sansan/Model/device/SensorHistory";
import SelectDeptList from "@/components/Sansan/SelectDeptList";
import SelectDeviceList from "@/components/Sansan/SelectDeviceListAll";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import BaseSearchForm from "@/components/SearchForm/BaseSearchForm";
import UploadFile from "@/components/Upload/UploadFile.vue";
import { MessageType } from "@/enums/messageEnum";
import { RouterPath } from "@/enums/routerPath";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { useDict } from "@/hooks/useDict";
import { PublicStore } from "@/stores/modules/public";
import { dataFormat } from "@/utils/format";
import { gotoPage } from "@/utils/routerUtil";
import { confirm, exportExcel, showMsg, showTips } from "@/utils/util";
import BasicDialog from "./components/basicDialog";
import { ComponentInternalInstance, getCurrentInstance } from "vue";
import "./index.scss";
import DialogBox from "@/components/DialogBox";
import { setSensor } from "@/api/modules/model/sensor";
import { ElMessage } from "element-plus";
export default defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const publicStore = PublicStore();
		const data = reactive({
			deptDeviceTree: [] as any[],
			initParam: { deptId: "", devSn: "", keyNot: "timestamp", deptIdNot: deptAnonymous } as any
		});

		const { variableDictMap, loadVariableDict } = useDict();

		const collapsedSearch = ref<boolean>(false);
		const dataCallback = (data: any) => {
			data.records = data.records.map((v: Variable.ResVariable) => {
				loadVariableDict(v);
				v.id = v.sn + v.key;
				return v;
			});
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};
		const sensorHistoryEl = ref();
		const btnList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			btnList.value = await useAuthButtons();
			// getDeptList().then(res => {
			// 	data.deptDeviceTree = res.result.records.children;
			// });
		});

		const detailDialog = reactive<any>({
			title: proxy?.$t("device_variable.dialog_title.var_config"),
			visible: false,
			detail: {}
		});
		const uploadFileEl = ref();
		const clickBtn = async (fn: string, row?: any) => {
			let selected: Variable.ResVariable[] = row ? (row.selectList ? row.selectList : [row]) : null;
			switch (fn) {
				case "detail":
				case "mod":
					if (selected.length != 1) {
						showMsg(proxy?.$t("device_variable.btnmsg.mod"), MessageType.warning);
						return;
					}
					detailDialog.detail = { ...selected[0] };
					detailDialog.visible = true;
					break;
				case "copy":
					if (selected.length != 1) {
						showMsg(proxy?.$t("device_variable.btnmsg.copy"), MessageType.warning);
						return;
					}
					detailDialog.detail = { ...selected[0] };
					detailDialog.detail.key = detailDialog.detail.key + "_copy";
					detailDialog.detail.label = detailDialog.detail.label + "_copy";
					detailDialog.visible = true;
					break;
				case "add":
					detailDialog.detail = {};
					detailDialog.visible = true;
					break;
				case "del":
					if (!selected.length) {
						showMsg(proxy?.$t("device_variable.btnmsg.del"), MessageType.warning);
						return;
					}
					confirm({ content: proxy?.$t("device_variable.btnmsg_content.del") }).then(flag => {
						flag && submitDel(selected);
					});
					break;
				case "sensorData":
					loadSensorData(selected[0]);
					break;
				case "gotoDevice":
					gotoPage(RouterPath.deviceDetail, { sn: selected[0].sn });
					break;
				case "reset": // 表单重置
					data.initParam.deptId = "";
					data.initParam.devSn = "";
					break;
				case "import":
					uploadFileEl.value.selectingFile();
					break;
				case "export":
					let res: any = await exportVariableExcel({});
					exportExcel(res.data, res.filename);
					break;
				case "send":
					if (selected.length == 0) {
						showMsg(proxy?.$t("device_variable.btnmsg.mod"), MessageType.warning);
						return;
					}
					if (selected.some((item: any) => selected[0].sn != item.sn)) {
						showMsg(proxy?.$t("device_variable.btnmsg.send"), MessageType.warning);
						return;
					}
					sendDialog.visible = true;
					sendDialog.list = selected;
					selected.map((item: any) => {
						sendDialog.detail[item.key] = item.value;
					});
					break;
			}
		};
		const loadSensorData = (row: Variable.ResVariable) => {
			let arr = row.key.split(".");
			let param: JsonSchemaEmitParam = {
				dataPath: row.key,
				dataType: row.type,
				dataKey: arr[arr.length - 1],
				dataValue: row.value,
				schemaInfo: { title: row.label }
			};
			sensorHistoryEl.value.loadData(param, row.sn);
		};
		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "onlineStatus", label: proxy?.$t("device_variable.tablist_label.onlineStatus"), width: 80 },
			{ prop: "sn", label: proxy?.$t("device_variable.tablist_label.sn"), width: 180, search: { slot: {} } },
			{ prop: "key", label: proxy?.$t("device_variable.tablist_label.key"), sortable: true },
			// { prop: "key", label: "变量标识", sortable: true },
			{ prop: "type", label: proxy?.$t("device_variable.tablist_label.type") },
			{ prop: "value", label: proxy?.$t("device_variable.tablist_label.value") },
			// { prop: "tags", label: "变量标签" },
			{ prop: "updateTime", label: proxy?.$t("device_variable.tablist_label.updateTime"), width: 170, sortable: true },
			{ prop: "deptName", label: proxy?.$t("device_variable.tablist_label.deptName"), width: 180, search: { slot: {} } },
			{ prop: "operation", label: proxy?.$t("device_variable.tablist_label.operation"), fixed: "right", width: 130 }
		];

		const proTable = ref<any>();
		const submitDel = async (dataInfo: Variable.ResVariable[]) => {
			let delParam: Variable.DelVariable = { snKey: {} };
			dataInfo.forEach(item => {
				if (!delParam.snKey[item.sn]) {
					delParam.snKey[item.sn] = [];
				}
				delParam.snKey[item.sn].push(item.key);
			});
			let res = await delInfo(delParam);
			let ok = showTips(res.code, proxy?.$t("device_variable.tips.delete"), res.message);
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.getTableList();
			}
		};
		const submitDetail = async () => {
			let api = detailDialog.detail.id ? modInfo : addInfo;
			let res = await api(detailDialog.detail);
			let ok = showTips(res.code, proxy?.$t("device_variable.tips.detail"), res.message);
			if (ok) {
				detailDialog.visible = false;
				proTable.value.getTableList();
			}
		};
		const handleChange = (e: any) => {
			data.initParam.sortField = e.prop;
			data.initParam.sortOrder = e.order == "ascending" ? "asc" : e.order == "descending" ? "desc" : "";
			// proTable.value.getTableList();
		};
		const sendDialog = reactive<any>({ visible: false, detail: {}, list: [] });
		const sendDialogConfirm = () => {
			sendDialog.list.map((item: any) => {
				if (item.type == "number") {
					sendDialog.detail[item.key] = Number(sendDialog.detail[item.key]);
				}
			});
			setSensor({
				idSn: sendDialog.list[0].sn,
				local: false,
				entire: false,
				data: sendDialog.detail
			}).then((res: any) => {
				if (res.code == 200) {
					sendDialog.visible = false;
					ElMessage.success("下发成功");
				} else {
					ElMessage.error(res.message || "下发失败");
				}
			});
		};
		return () => {
			return (
				<div class="variable-list">
					{/* <el-scrollbar class="left-tree h-full">
						<TreeFilter data={data.deptDeviceTree} label="deptName" />
					</el-scrollbar> */}
					<div class="flex-1">
						<SensorHistory ref={sensorHistoryEl} />
						<DialogBox v-model:visible={sendDialog.visible} width="500" title="参数下发" onConfirm={sendDialogConfirm}>
							<el-form label-width="200px">
								{sendDialog.list.map((item: any) => {
									return (
										<el-form-item label={item.key}>
											<el-input v-model={sendDialog.detail[item.key]} />
										</el-form-item>
									);
								})}
							</el-form>
						</DialogBox>
						<BasicDialog
							width="850px"
							title={detailDialog.title}
							v-model:visible={detailDialog.visible}
							detail={detailDialog.detail}
							onSubmit={submitDetail}
						></BasicDialog>
						<UploadFile
							style="display: none;"
							ref={uploadFileEl}
							api={importVariableExcel}
							headers={{ Authentication: publicStore.token }}
						/>
						{collapsedSearch.value ? null : (
							<BaseSearchForm class="mb-2">
								<el-form
									class="flex pt-4 pl-4 pr-4 bg-white"
									style="flex-wrap: wrap;"
									onKeyup={(e: KeyboardEvent) => (e.keyCode == 13 ? proTable.value.getTableList() : null)}
								>
									<el-form-item class="search-item" label={proxy?.$t("device_variable.search_label.deptName")}>
										<div style="width:180px">
											<SelectDeptList detail={data.initParam} appendChild onChange={val => (data.initParam.deptId = val.id)} />
										</div>
									</el-form-item>
									<el-form-item class="search-item" label={proxy?.$t("device_variable.search_label.name")}>
										<el-input
											v-model={data.initParam.devName}
											placeholder={proxy?.$t("device_variable.search_placeholder.name")}
											style="width:160px"
										/>
									</el-form-item>
									<el-form-item class="search-item" label={proxy?.$t("device_variable.search_label.sn")}>
										<el-input
											v-model={data.initParam.devSn}
											placeholder={proxy?.$t("device_variable.search_placeholder.sn")}
											style="width:160px"
										/>
									</el-form-item>
									<el-form-item class="search-item">
										<el-button type="primary" class="iconfont iconsearch" onClick={() => proTable.value.getTableList()}>
											{proxy?.$t("common.btn.search")}
										</el-button>
									</el-form-item>
								</el-form>
							</BaseSearchForm>
						)}
						<ProTable
							ref={proTable}
							title={btnList.value.length ? "" : proxy?.$t("device_variable.tabtitle.list_manage")}
							columns={columns}
							custSearch
							onSearchCollapsed={val => {
								collapsedSearch.value = val;
							}}
							requestApi={getPageList}
							initParam={data.initParam}
							dataCallback={dataCallback}
							onSortChange={handleChange}
							onReset={() => {
								clickBtn("reset");
							}}
						>
							{{
								"search-sn": () => {
									return <SelectDeviceList v-model={data.initParam.devSn} />;
								},
								tableHeader: (scope: any) => {
									return (
										<>
											{btnList.value
												?.filter((item: any) => !item.btnGroup || item.btnGroup != "3")
												.map((item: any) => {
													return (
														<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
															<i class={`iconfont ${item.icon}`}></i>
															{item.menuName}
														</el-button>
													);
												})}

											{btnList.value.find((item: any) => item.btnGroup == "3") && (
												<el-dropdown
													trigger="click"
													v-slots={{
														dropdown: () => {
															return (
																<el-dropdown-menu>
																	{btnList.value
																		.filter((item: any) => item.btnGroup == "3")
																		.map((item: any) => {
																			return (
																				<>
																					{item.path == "import" ? (
																						<>
																							<UploadFile
																								style="display: none;"
																								ref={uploadFileEl}
																								api={importVariableExcel}
																								headers={{ Authentication: publicStore.token }}
																							/>
																							<el-dropdown-item
																								onClick={() => clickBtn("import", { selectedList: proTable.value.selectedList })}
																							>
																								{item.menuName}
																							</el-dropdown-item>
																						</>
																					) : item.path == "export" ? (
																						<el-dropdown-item
																							onClick={() => clickBtn("export", { selectedList: proTable.value.selectedList })}
																						>
																							{item.menuName}
																						</el-dropdown-item>
																					) : null}
																				</>
																			);
																		})}
																</el-dropdown-menu>
															);
														}
													}}
												>
													<el-button type="primary" plain>
														{proxy?.$t("device_variable.btn.bulk")}
														<span class="iconfont iconchevron-down pl-1"></span>
													</el-button>
												</el-dropdown>
											)}
										</>
									);
								},
								type: (scope: any) => {
									return TYPE_NAME[scope.row.type] || scope.row.type || TYPE_NAME[typeof scope.row.value];
								},
								key: (scope: any) => {
									return (
										<div class="truncate cursor-pointer primary-color" onClick={() => clickBtn("detail", scope.row)}>
											{scope.row.label || scope.row.key}
										</div>
									);
								},
								sn: (scope: any) => {
									return (
										<div class="truncate cursor-pointer primary-color" onClick={() => clickBtn("gotoDevice", scope.row)}>
											{scope.row.devName || scope.row.sn}
										</div>
									);
								},
								tags: (scope: any) => {
									return (
										<>
											{scope.row.param?.tags?.map((v: string) => {
												return (
													<el-tag class="mr-1" closable={false} disable-transitions={false}>
														{v}
													</el-tag>
												);
											})}
										</>
									);
								},
								value: (scope: any) => {
									return (
										<div class="truncate cursor-pointer primary-color" onClick={() => clickBtn("sensorData", scope.row)}>
											{variableDictMap.value[scope.row.sn + "_" + scope.row.key]?.find(dict => dict.key == scope.row.value)
												?.label ||
												scope.row.value ||
												"--"}
											{scope.row.config?.unit || ""}
										</div>
									);
								},
								createTime: (scope: any) => {
									return dataFormat("datetime", scope.row.createTime);
								},
								onlineStatus: (scope: any) => {
									return (
										<OnlineStatus
											v-model={scope.row.onlineStatus}
											onlineLabel={proxy?.$t("device_variable.status.online")}
											offlineLabel={proxy?.$t("device_variable.status.offline")}
										/>
									);
								},
								operation: (scope: any) => {
									return (
										<>
											{btnList.value
												.filter((item: any) => item.path == "del")
												.map((item: any) => {
													return (
														<el-popconfirm
															title={proxy?.$t("device_variable.confirm_title.delete")}
															popper-class="jsonform-tooltip"
															onConfirm={() => clickBtn(item.path, scope.row)}
														>
															{{
																reference: () => {
																	return (
																		<el-link type="danger">
																			<i class="iconfont icontrash-2"></i>
																			{item.menuName}
																		</el-link>
																	);
																}
															}}
														</el-popconfirm>
													);
												})}
											{!btnList.value.find((item: any) => item.path == "del") ? (
												<el-link type="danger" disabled>
													<i class="iconfont icontrash-2"></i>
													{proxy?.$t("device_variable.operate.delete")}
												</el-link>
											) : null}
											<el-link
												type="primary"
												link
												class="iconfont iconbx-file"
												onClick={() => {
													clickBtn("detail", scope.row);
												}}
											>
												{proxy?.$t("device_variable.operate.detail")}
											</el-link>
										</>
									);
								},
								empty: () => {
									return (
										<div>
											<Empty
												class="text-left leading-6"
												subtitle={proxy?.$t("device_variable.empty.subtitle")}
												btnText={proxy?.$t("device_variable.empty.btntext")}
												onAdd={(scope: any) => {
													clickBtn("add", scope);
												}}
											/>
										</div>
									);
								}
							}}
						</ProTable>
					</div>
				</div>
			);
		};
	}
});
